﻿// Write a method that adds two positive integer numbers represented as arrays of digits 
// (each array element arr[i] contains a digit; the last digit is kept in arr[0]).
// Each of the numbers that will be added could have up to 10 000 digits.

using System;
using System.Collections.Generic;

class SumBigNumbersAsArray
{
    static void Main()
    {
        int[] numberArray1 = { 0, 8, 2, 9, 9, 9, 0, 1 };
        int[] numberArray2 = { 4, 3, 0, 2, 0, 0, 1, 0, 0, 0 };

        int[] sum = SumReversedBigNumber(numberArray1, numberArray2);

        Console.WriteLine(String.Join("", sum));
    }

    private static int[] SumReversedBigNumber(int[] numberArray1, int[] numberArray2)
    {
        int lengthArray1 = numberArray1.Length;
        int lengthArray2 = numberArray2.Length;
        if (lengthArray1 == 0 && lengthArray2 == 0)
        {
            return new int[] { };
        }
        else
        {
            int maxLength = Math.Max(lengthArray1, lengthArray2);
            int remainder = 0;
            List<int> result = new List<int>(maxLength);
            for (int i = 0; i < maxLength; i++)
            {
                int sum = 0;
                if (i < lengthArray1 && i < lengthArray2)
                {
                    sum = numberArray1[i] + numberArray2[i];
                }
                else if (i < lengthArray1)
                {
                    // second array end
                    sum = numberArray1[i];
                }
                else
                {
                    // first array end
                    sum = numberArray2[i];
                }

                if (remainder != 0)
                {
                    sum += remainder;
                }
                remainder = sum / 10;
                int digit = sum % 10;
                result.Add(digit);
            }

            if (remainder != 0)
            {
                result.Add(remainder);
            }

            // remove leading zero
            for (int i = result.Count - 1; i > 0; i--)
            {
                if (result[i] == 0)
                {
                    result.RemoveAt(i);
                }
                else
                {
                    break;
                }
            }

            return result.ToArray();
        }
    }
}